package edu.ynu.se.xiecheng.achitectureclass.service;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OssService {
    @Autowired
    private OSS ossClient;
    
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    
    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    /**
     * 将网络图片上传到OSS
     */
    public String uploadFromUrl(String imageUrl, String deviceSerial) {
        try {
            // 从URL下载图片
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            
            // 生成OSS存储路径
            String fileName = generateFileName(deviceSerial);
            
            // 上传到OSS
            ossClient.putObject(bucketName, fileName, inputStream);
            
            // 返回可访��的URL
            return urlPrefix + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("上传图片到OSS失败", e);
        }
    }
    
    /**
     * 生成文件名
     */
    private String generateFileName(String deviceSerial) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return String.format("camera/%s/%s.jpg", deviceSerial, timestamp);
    }
} 